using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Timers;
using System.Windows.Forms;

namespace TextSupport
{
	public class TextFrameController
	{
		TextFrame _tf;
		TextFrameView _view;
		bool _caretEnabled;

		bool _isEditing;
		public bool EditMode
		{
			get { return _isEditing; }
		}

		public TextFrameController(TextFrame tf, TextFrameView view)
		{
			_tf = tf;
			_view = view;
		}

		public void StartCaret()
		{
			_caretEnabled = true;
			_view.Surface.RestartCaretTimer();
			_view.DrawCaret();
		}

		public void CaretTimerTick()
		{
			if (_caretEnabled)
				_view.ToggleCaret();
		}

		public void EndCaret()
		{
			_caretEnabled = false;
			_view.EraseCaret();
		}

		public void BeginEdit()
		{
			StartCaret();

			Debug.Assert(!_isEditing);
			_isEditing = true;
		}

		public void EndEdit()
		{
			EndCaret();

			Debug.Assert(_isEditing);
			_isEditing = false;
		}

		public void UpdateLayout()
		{
			_tf.UpdateLayout();
			_view.UpdateLayout();
			_view.Surface.Invalidate();
		}

		public void SetText(string text)
		{
			_tf._text = text;
			_tf.UpdateLayout();
			UpdateLayout();
		}

		public bool KeyPress(char ch)
		{
			EndCaret();

			// Need to insert this character into the string, and then
			// relay the string out...
			int insertionPoint = _view.CaretIndex;

			string origText = _tf.Text;
			string newText = origText.Insert(insertionPoint, string.Format("{0}", ch));
			SetText(newText);

			_view.OnCursorRight();

			StartCaret();

			return true;
		}

		public bool KeyDown(KeyEventArgs e)
		{
			EndCaret();

			switch (e.KeyCode)
			{
				case Keys.Left:
					_view.OnCursorLeft();
					break;

				case Keys.Right:
					_view.OnCursorRight();
					break;

				default:
					return false;
			}

			StartCaret();

			return true;
		}

		public bool KeyUp(KeyEventArgs e)
		{
			return false;
		}
	}
}
